<?php

namespace IMT\AttachmentsBundle\Controller;

use Symfony\Component\HttpFoundation\Response;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use IMT\AttachmentsBundle\Entity\Attachment;
use IMT\AttachmentsBundle\Form\AttachmentType;

/**
 * Attachment controller.
 *
 */
class AttachmentController extends Controller
{
	/**
	 * Upload les fichiers envoyés par plupload
	 */
	public function uploadAction()
	{
		$request = $this->getRequest();
		$uploadedFile = $request->files->get('uploaded_attachments');
		$securityContext = $this->get('security.context');
	
		$result = array('jsonrpc' => '2.0');
	
		if(null === $uploadedFile){
			$result['error'] = array(
					'code' => 400,
					'message' => 'Aucun fichier n\'a été reçu'
			);
			return new Response(json_encode($result), 200);
		}
	
		$entity = new Attachment();
		$entity->setName($uploadedFile->getClientOriginalName());
		$entity->setFile($uploadedFile);
		$entity->setFileBase64(base64_encode(file_get_contents($uploadedFile)));
		$entity->setMime($uploadedFile->getMimeType());
		$entity->setExtension($uploadedFile->guessExtension());	
		$entity->setUser($securityContext->getToken()->getUser());	
		
		try {
			$em = $this->getDoctrine()->getEntityManager();
			$em->persist($entity);
			$em->flush();
		} catch(\PDOException $e){
			$result['error'] = array(
				'code' => 500,
				'message' => 'Le serveur n\'a pas pu sauvegarder la pièce jointe',
				'debug' => '[Message] : '.$e->getMessage()."\n[Stack] : ".$e->getTraceAsString()
			);
			return new Response(json_encode($result), 200);
		}
		
		$result['result'] = array(
			'id' => $entity->getId(),	
			'path' => $this->get('router')->generate('imt_attachment_down', array('ids' => $entity->getId()))
		);
		
		return new Response(json_encode($result), 200);
		
	}
	
    /**
     * Lists all Attachment entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('IMTAttachmentsBundle:Attachment')->findAll();

        return $this->render('IMTAttachmentsBundle:Attachment:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Finds and displays a Attachment entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Attachment entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('IMTAttachmentsBundle:Attachment:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to create a new Attachment entity.
     *
     */
    public function newAction()
    {
        $entity = new Attachment();
        $form   = $this->createForm(new AttachmentType(), $entity);

        return $this->render('IMTAttachmentsBundle:Attachment:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a new Attachment entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new Attachment();
        $form = $this->createForm(new AttachmentType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('attachment_show', array('id' => $entity->getId())));
        }

        return $this->render('IMTAttachmentsBundle:Attachment:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Attachment entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Attachment entity.');
        }

        $editForm = $this->createForm(new AttachmentType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('IMTAttachmentsBundle:Attachment:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing Attachment entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Attachment entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new AttachmentType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('attachment_edit', array('id' => $id)));
        }

        return $this->render('IMTAttachmentsBundle:Attachment:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a Attachment entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Attachment entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('attachment'));
    }
    
    public function deleteAjaxAction($id)
    {
    	$return = array();
    	$em = $this->getDoctrine()->getEntityManager();
    	$entity = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($id);
    	
    	if (!$entity) {
    		throw $this->createNotFoundException('Unable to find Attachment entity.');
    	}
    	
    	$em->remove($entity);
    	$em->flush();
    	
    	$return['result'] = array(
    		'status' => 200,
    		'response' => null
    	);
    	
    	return new Response(json_encode($return), 200);
    }
    
    public function downloadAction($ids){
    	$idsTemp = explode(';', $ids);
    	$attachments = array();
    	
    	$em = $this->getDoctrine()->getEntityManager();
    	$helper = $this->container->get('vich_uploader.templating.helper.uploader_helper');
    	
    	foreach($idsTemp as $id){
    		$id = intval($id);
    		
    		if($id){
	    		$attachment = $em->getRepository('IMTAttachmentsBundle:Attachment')->find($id);
	    		 
	    		if($attachment)
	    			$attachments[] = $attachment;
    		}
    	}
    	   	
    	$countAttachments = sizeof($attachments);
    	
    	if($countAttachments > 1){
    		
    		$zipname = 'archive.zip';
    		$path = $this->get('kernel')->getRootDir() . '/../web/tmp/';
    		echo $path.$zipname;
    		exit;
    		$zip = new \ZipArchive();
    		$zip->open($path.$zipname, \ZipArchive::CREATE);
    		foreach($attachments as $attachment){
    			$zip->addFile($helper->asset($attachment, 'file'), $attachment->getName());
    		}
    		$zip->close();
    		
    		header('Content-type: application/zip');
    		header('Content-Disposition: attachment; filename="'.$zipname.'"');
    		header("Pragma: no-cache");
    		header("Expires: 0");
    		readfile($path.$zipname);
    		exit;
    	} else if($countAttachments == 1){
    	 	header("Cache-Control: public");
    		header('Content-type: '.$attachments[0]->getMime());
    		header('Content-Disposition: attachment; filename="'.$attachments[0]->getName().'"');
    		echo file_get_contents($attachments[0]->getFile());
    		exit;
    	} else {
    		throw new \InvalidArgumentException('Les paramètres reçus sont incorrects', '400');
    	}
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}
